/**
 * User: antosha
 * Date: 1/18/13
 */

/**
 * Table module
 * @constructor
 * @extends {jst.BaseModule}
 */
jst.Table = function(sel) {
    this._columns = [];
    this._rowData = [];
    this._table = $(sel || '#temp_selector');
    this._table.empty();

    //todo mb replace with fill function
    this._fillRowData = function() {
        var rows = this._rowData || [], row, tr;

        for(var i = 0; i < rows.length; i++) {
            row = rows[i];
            tr = $('<tr></tr>');

            for(var j = 0; j < row.length; j++) {
                tr.append('<td>' + row[j] + '</td>');
            }
            tr.on('click', function() {
                $(this).css('borderWidth', '2px');
            });

            this._table.append(tr);
        }
    };

    this._fillColumns = function() {
        var clm = this._columns || [];
        var tbl = this._table;
        var thead = $('<thead></thead>'), th;

        if(clm.length > 0) {
            var tr = $('<tr></tr>');

            for(var i = 0; i < clm.length; i++) {
                th = $('<th></th>');
                th.html(clm[i]);

                th.on('click', function() {
                    var t = $(this), cond = t.hasClass('sortUp');
                    tbl.find('th').removeClass('sortDown').removeClass('sortUp');

                    if(cond) {
                        t.addClass('sortDown');
                    } else {
                        t.addClass('sortUp');
                    }
                });

                tr.append(th);
            }
        }

        thead.append(tr);
        this._table.append(thead);
    };
};
jst.inherit(jst.Table, jst.BaseModule);

jst.Table.prototype = {
    setRowData : function (data) {
        this._rowData = data;
        this._fillRowData();
    },
    getRowData : function () {
        return this._rowData;
    },
    setColumns : function (data) {
        this._columns = data;
        this._fillColumns();
    },
    getColumns : function () {
        return this._columns;
    }
};